<template>
  <div class="container">
    <el-row>
      <el-col class="top-search">
        <el-input
          v-model="selectObj.value"
          :placeholder="$t('please_enter_content')"
          clearable
          class="w-400"
        >
          <el-select
            slot="prepend"
            v-model="selectObj.key"
            :placeholder="$t('please_select')"
            class="w-180"
          >
            <el-option :label="$t('we_media_name')" value="nickName" />
            <el-option :label="$t('we_media_id')" value="mediaUserId" />
            <el-option :label="$t('name')" value="realName" />
          </el-select>
        </el-input>
        <el-input
          v-model="listQuery.memberId"
          :placeholder="$t('member_id')"
          class="w-180"
          clearable
        />

        <el-select
          v-model="listQuery.subsidyType"
          :placeholder="$t('please_select')"
          class="w-180"
        >
          <el-option :value="null" :label="$t('income_plan')" />
          <el-option
            v-for="(label, value) in SUBSIDY_TYPE_MAP"
            :value="value"
            :label="$t(label)"
            :key="value"
          />
        </el-select>

        <el-select
          :placeholder="$t('please_select')"
          v-model="listQuery.userStatus"
          class="w-120"
        >
          <el-option :value="null" :label="$t('status')" />
          <el-option :value="1" :label="$t('normal')" />
          <el-option :value="0" :label="$t('stop_using')" />
        </el-select>
        <label for="">{{ $t('time_of_income') }}:</label>
        <el-date-picker
          v-model="datePicker"
          class="w-240"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
        />
        <el-button type="primary" @click="search()">{{
          $t('search')
        }}</el-button>
      </el-col>

      <el-col>
        <span class="m-l-10"
          >{{ $t('total_gold_coin_revenue') }}: {{ totalCoinAmount }}</span
        >
        <el-button
          class="m-l-10"
          :class="{ 'sort-color': listQuery.orderField == 'coinAmount' }"
          @click="sort('coinAmount')"
          >{{ $t('gold_coin_income') }}
          <span class="sort-arrow">
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 'coinAmount' &&
                  listQuery.orderBy == 'desc'
              }"
              class="el-icon-caret-top sort-arrow__top"
            />
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 'coinAmount' &&
                  listQuery.orderBy != 'desc'
              }"
              class="el-icon-caret-bottom sort-arrow__bottom"
            />
          </span>
        </el-button>
        <span class="m-l-10"
          >{{ $t('total_money_revenue') }}: ${{ totalMoneyAmount }}</span
        >
        <el-button
          class="m-l-10"
          :class="{ 'sort-color': listQuery.orderField == 'moneyAmount' }"
          @click="sort('moneyAmount')"
          >{{ $t('money_income') }}
          <span class="sort-arrow">
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 'moneyAmount' &&
                  listQuery.orderBy == 'desc'
              }"
              class="el-icon-caret-top sort-arrow__top"
            />
            <i
              :class="{
                'defalut-color':
                  listQuery.orderField == 'moneyAmount' &&
                  listQuery.orderBy != 'desc'
              }"
              class="el-icon-caret-bottom sort-arrow__bottom"
            />
          </span>
        </el-button>
        <el-button type="primary" @click="toExport()">{{
          $t('export_doc')
        }}</el-button>
      </el-col>

      <el-col class="p-t-20">
        <el-table
          v-loading="listLoading[0]"
          :data="listData"
          border
          fit
          highlight-current-row
        >
          <el-table-column
            :label="$t('serial_number')"
            type="index"
            width="150"
          />

          <el-table-column
            :label="$t('we_media_name')"
            prop="nickName"
            align="center"
            width="120"
          />

          <el-table-column
            :label="$t('we_media_id')"
            prop="mediaUserId"
            align="center"
            width="380"
          />

          <el-table-column :label="$t('name')" prop="realName" align="center" />

          <el-table-column :label="$t('income_plan')" align="center">
            <template slot-scope="scope">
              <span>{{ $t(SUBSIDY_TYPE_MAP[scope.row.subsidyType]) }}</span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('status')"
            prop="activityName"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ stateMap[scope.row.userStatus] }}</span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('gold_coin_income')"
            prop="coinAmount"
            align="center"
          />

          <el-table-column
            :label="$t('money_income') + '($)'"
            prop="moneyAmount"
            align="center"
          />

          <el-table-column :label="$t('operation')" align="center" width="180">
            <template slot-scope="scope">
              <el-button
                type="primary"
                @click="checkDetails(scope.row.memberId)"
              >
                {{ $t('view_income_detail') }}
              </el-button>
              <el-button
                type="primary"
                @click="viewUserSettings(scope.row.mediaUserId)"
              >
                {{ $t('view_user_settings') }}
              </el-button>
              <el-button
                type="primary"
                @click="viewUserPortrait(scope.row.mediaUserId)"
              >
                {{ $t('view_creative_portrait') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="total > 0" class="block fr">
          <el-pagination
            :current-page="listQuery.pageNum"
            :page-sizes="[15, 20, 30]"
            :page-size="listQuery.pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="val => handlePageChange(val, 'size')"
            @current-change="val => handlePageChange(val, 'page')"
          />
        </div>
      </el-col>
    </el-row>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="$t('income_detail')"
      width="75%"
    >
      <el-table
        v-loading="listLoading[1]"
        :data="detailListData"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          :label="$t('time')"
          prop="createTime"
          align="center"
          width="100"
        />

        <el-table-column :label="$t('single_day_earnings')" align="center" width="160">
          <template slot-scope="{ row }">
            <span v-if="row.revenueType == 'money'"
              >${{ row.moneyAmount }}</span
            >
            <span v-else> {{ row.coinAmount }}{{ $t('coins') }} </span>
          </template>
        </el-table-column>

        <el-table-column :label="$t('income_consist')" align="center">
          <template slot-scope="{ row }">
            <div v-for="(item, index) in row.details" :key="index">
              <p>
                {{ $t(INCOME_TYPE_MAP[item['incomeType']]) }}
                <span v-if="row.revenueType == 'money'">
                  ${{ item['moneyAmount'] }}</span
                >
                <span v-if="row.revenueType == 'coin'">
                  {{ item['coinAmount'] }}{{ $t('coins') }}</span
                >
                <span v-if="item['flowType'] == 1"
                  >( {{ $t(FLOW_TYPE_MAP[item['flowType']]) }}:
                  {{ item['totalQuantity'] }} = {{ item['realQuantity'] }} +
                  {{ item['totalQuantity'] - item['realQuantity'] }} )</span
                >
                <span v-else
                  >( {{ $t(FLOW_TYPE_MAP[item['flowType']]) }}:
                  {{ item['totalQuantity'] }} )</span
                >
              </p>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import timeUtils from '@/utils/timeHandle.js';
import {
  getSubsidyListApi,
  getSubsidyDetailApi
} from '@/api/wemediaRevenueAnalysis.js';
import {
  FLOW_TYPE_MAP,
  INCOME_TYPE_MAP,
  SUBSIDY_TYPE_MAP
} from '@/constants/index.js';
import { getToken } from '@/utils/auth';

export default {
  data() {
    return {
      SUBSIDY_TYPE_MAP,
      INCOME_TYPE_MAP,
      FLOW_TYPE_MAP,
      datePicker: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 7,
          'date'
        ),
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 1,
          'date'
        )
      ],
      selectObj: {
        key: 'nickName',
        value: null
      },
      dialogVisible: false,
      listData: [],
      detailListData: [],
      listLoading: [false, false],
      total: 0,
      totalMoneyAmount: null,
      totalCoinAmount: null,
      listQuery: {
        userLevel: null,
        subsidyType: null,
        userStatus: null,
        beginTime: null,
        endTime: null,
        memberId: null,
        orderBy: 'desc',
        orderField: '', // 金币排序：coinAmount，零钱排序：moneyAmount
        size: 15,
        page: 1
      },
      stateMap: {
        0: this.$t('stop_using'),
        1: this.$t('normal')
      }
    };
  },

  created() {
    const { mediaUserId } = this.$route.query;
    if (mediaUserId) {
      this.selectObj = {
        key: 'mediaUserId',
        value: mediaUserId
      };
      this.datePicker = [];
    }
    
    this.search();
  },

  methods: {
    search() {
      const { key, value } = this.selectObj;

      if (key == 'mediaUserId' && value && value % 1 !== 0) {
        this.$message.warning(this.$t('we_media_id_must_be_number'));
        return;
      }

      this.listQuery.beginTime =
        (this.datePicker && this.datePicker[0]) || null;
      this.listQuery.endTime = (this.datePicker && this.datePicker[1]) || null;

      delete this.listQuery.mediaUserId;
      delete this.listQuery.nickName;
      delete this.listQuery.realName;

      if (value && key) {
        this.listQuery[key] = value;
      }
      this.listQuery.page = 1;
      this.getList();
    },

    sort(key) {
      const { orderBy, orderField } = this.listQuery;
      if (key === orderField) {
        this.listQuery.orderBy = orderBy == 'desc' ? 'asc' : 'desc';
      } else {
        this.listQuery.orderBy = 'asc';
        this.listQuery.orderField = key;
      }

      this.listQuery.page = 1;
      this.getList();
    },

    checkDetails(memberId) {
      this.dialogVisible = true;
      this.getDetailList(memberId);
    },

    handlePageChange(val, key) {
      this.listQuery[key] = val;
      this.getList();
    },

    async getList() {
      this.listLoading[0] = true;
      try {
        const { code, data, msg } = await getSubsidyListApi(this.listQuery);
        this.listLoading[0] = false;
        if (code == 200) {
          this.listData = data.list || [];
          this.total = Number(data.total) || 0;
          this.totalMoneyAmount = Number(data.totalMoneyAmount) || 0;
          this.totalCoinAmount = Number(data.totalCoinAmount) || 0;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.listLoading[0] = false;
      }
    },

    async getDetailList(memberId) {
      const { beginTime, endTime } = this.listQuery;
      this.listLoading[1] = true;

      try {
        const { code, data, msg } = await getSubsidyDetailApi({
          beginTime,
          endTime,
          memberId
        });
        this.listLoading[1] = false;
        if (code == 200) {
          this.detailListData = this.formatDetailData(data || []);
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.listLoading[1] = false;
      }
    },

    // 通过moneyAmount coinAmount是否有值判断收益类型
    formatDetailData(data = []) {
      return data.map(item => {
        if (item.moneyAmount) {
          // eslint-disable-next-line no-param-reassign
          item.revenueType = 'money';
        } else {
          // eslint-disable-next-line no-param-reassign
          item.revenueType = 'coin';
        }

        return item;
      });
    },

    viewUserSettings(mediaUserId) {
      const url = `${process.env.NEWS_ADMIN}mediaAccount?mediaUserId=${mediaUserId}`
      window.open(url);
    },

    viewUserPortrait(mediaUserId) {
      const url = `${process.env.DATA_ADMIN}/#/recommend_analysis/WemediaPortrait?mediaUserId=${mediaUserId}`;
      window.open(url);
    },

    toExport() {
      const xhh = new XMLHttpRequest();
      xhh.open('post', `${process.env.BASE_API}/v1/subsidy/export`);
      xhh.setRequestHeader('X-Token', getToken());
      xhh.setRequestHeader('content-type', 'application/json;charset=UTF-8');
      xhh.responseType = 'blob';
      xhh.onreadystatechange = function() {
        if (xhh.readyState === 4 && xhh.status === 200) {
          const blob = new Blob([xhh.response]);
          const csvUrl = URL.createObjectURL(blob);
          const link = document.createElement('a');
          let fileName = xhh
            .getResponseHeader('Content-Disposition')
            .split(';')[1]
            .split('filename=')[1];
          const fileNameUnicode = xhh
            .getResponseHeader('Content-Disposition')
            .split('filename*=')[1];
          if (fileNameUnicode) {
            fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
          }

          document.body.appendChild(link);
          link.href = csvUrl;
          link.target = '_blank';
          link.id = 'linkId';
          link.className = 'linkId';
          link.download = decodeURI(fileName);
          document.getElementById('linkId').click();
          link.remove();
        }
      };
      const query = { ...this.listQuery, page: 1, size: 100000 };
      xhh.send(JSON.stringify(query));
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;
  .top-search {
    margin: 10px 0;
    label {
      font-size: 12px;
      font-weight: 400;
      margin-right: 5px;
    }
  }
  .w-120 {
    width: 120px;
  }
  .w-180 {
    width: 180px;
  }
  .w-240 {
    width: 240px;
  }
  .w-400 {
    width: 400px;
  }
  .p-t-20 {
    padding-top: 20px;
  }

  .m-l-10 {
    margin-left: 10px;
  }

  .fr {
    float: right;
    padding-top: 20px;
  }

  .sort-arrow {
    padding-right: 10px;
    &__top {
      position: absolute;
      top: 70px;
    }
    &__bottom {
      position: absolute;
      top: 78px;
    }
  }

  .defalut-color {
    color: #606266;
  }

  .sort-color {
    color: #409eff !important;
  }
}
</style>
